from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os

from html import CheckBox, DropDown, MultiSelect, RadioButton #importing the html wrappers.
import validate #import validation
import tables
import main
import datetime
import staticInits 
import cgi #for escaping html chars in forms
import re

class AddTa(webapp.RequestHandler):
    """
    This class deals with the admin add ta view.
    """

    def __init__(self):
        webapp.RequestHandler.__init__(self) #parent constructor call
        
        self.currentSemester = tables.AppState.get_by_key_name('currentState').semester
        
        self.stickyValues = dict()
        self.stickyValues['firstName'] = ""
        self.stickyValues['lastName'] = ""
        self.stickyValues['eid'] = ""
        
        self.tas = dict()
        for ta in db.GqlQuery("SELECT * FROM Ta WHERE semester = :currentSemester", currentSemester = self.currentSemester): self.tas[ta.eid] = ta

        self.errorMessages = []
        
    def get(self):
        """
        Calls renderTemplate() for this class.
        """
        self.renderTemplate()

    def post(self):
        """
        Evaluates form submission. Calls renderTemplate() for this class.
        """        
        
        firstName = self.request.get('firstName')
        lastName = self.request.get('lastName')
        eid = self.request.get('eid').lower()


        if(not validate.validateFirstName(firstName)):
            self.errorMessages.append("Please give a valid first name.")
        if(not validate.validateLastName(lastName)):
            self.errorMessages.append("Please give a valid last name.")
        if(not validate.validateEid(eid)):
            self.errorMessages.append("Please give a valid eid.")
        if(not validate.validateUniqueEid(eid, self.currentSemester)):
            self.errorMessages.append("The EID you have entered is already in the system.")

        
        if len(self.errorMessages) == 0:
            newTa = tables.Ta(firstName = firstName, lastName = lastName, eid = eid, semester = self.currentSemester, submitted = False)
            newTa.put()
            self.tas[newTa.eid] = newTa
        else:
            self.stickyValues['firstName'] = firstName
            self.stickyValues['lastName'] = lastName
            self.stickyValues['eid'] = eid
                
        self.renderTemplate()
    
    def renderTemplate(self, addValid = "") :
        """
        Renders the Template addTa.html for this class.
        """
        
        sortedTas = self.tas.values()
        sortedTas.sort(key = lambda ta : ta.lastName.lower())
        
        #setting up template dictionary
        templateValues = {
            'tas' : sortedTas,
            'badFirstName' : self.stickyValues['firstName'],
            'badLastName' : self.stickyValues['lastName'],
            'badEid' : self.stickyValues['eid'],
            'errorMessages' : self.errorMessages,
            'currentSemester' : self.currentSemester,
        }


        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'addTa.html')
        self.response.out.write(template.render(path, templateValues))

application = webapp.WSGIApplication([('/admin/addTa', AddTa)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
